local ROT = require 'rot'

local state = ROT.Class:extend()

function state:init(game, play, stack)
    self.game = game
    self.play = play
    self.selected = {}
    self.stack = game.scene.stack:getCell(game.player.x, game.player.y)
end

local FIRST_KEY = ('a'):byte() - 1
local DIM = { 120, 120, 120 }
local BRIGHT = { 240, 240, 240 }

function state:update()
    if self.stack == nil or #self.stack < 1 then
        self.game:log("There's nothing here.")
        self.game:popState()
        return
    end
    local play = self.play
    local display = self.game.display
    display:clear()
    display:write(tostring(#self.stack) .. ' items here:', 1, 1)
    for i = 1, #self.stack do
        display:write(string.char(i + FIRST_KEY) .. ') ' .. self.stack[i].name, 1, 2 + i,
            self.selected[i] and BRIGHT or DIM)
    end
    local s = '(a-z selects, [esc] cancels, [enter] confirms)'
    display:write(s, display:getWidth() - #s, display:getHeight())
end

function state:keypressed(key)
    local game = self.game
    if key == '\27' then
        game:popState()
    elseif key == '\n' then
        local playerstuff = self.game.player.stuff
        for i = #self.stack, 1, -1 do
            if self.selected[i] then
                game:log('You take the ', self.stack[i].name, '.')
                game.scene:passTime()
                playerstuff[#playerstuff + 1] = table.remove(self.stack, i)
            end
        end
        game:popState()
    else
        local index = key:byte() - FIRST_KEY
        if self.stack[index] then
            self.selected[index] = not self.selected[index]
        end
    end
end

return state
